import cloud from '@lafjs/cloud'
let dbName = "admin-users"

export default async function (ctx: FunctionContext) {
  let res = await cloud.nw.db.findByWhereJson({
    dbName, whereJson: { account: ctx.body.account },
  });
  //console.log("查询到的", res)
  if (!res.roles.length) return
  let menuIds = []
  const result = await cloud.invoke('admin/system/role', { ...ctx, body: { type: 'query' } })
  for (let index = 0; index < result.data.length; index++) {
    const element = result.data[index];
    if (res.roles.includes(element._id)) menuIds.push(...element.menuIds)
  }
  menuIds = cloud.utils.unique(menuIds)
  //console.log("角色涉及到的id", menuIds)
  const { data } = await cloud.invoke('admin/system/menu', { ...ctx, body: { type: 'query' } })
  // console.log("菜单列表", data)
  let menuIdList = []
  for (let index = 0; index < data.length; index++) {
    const element = data[index];
    if (menuIds.includes(element._id)) menuIdList.push(element)
  }
  //console.log("展示的菜单", menuIdList)

  //如果账户是admin的话,则返回全部菜单
  if (res.account == "admin") menuIdList = data

  let items = cloud.utils.transformArray(cloud.utils.deepcopy(menuIdList), "_id", "parentId");
  let menusTree = cloud.utils.sortItems(items, "asc", "orderNum");

  return cloud.utils.requestReturn({
    data: {
      userInfo: res,
      menus: menuIdList,
      menusTree
    }
  })
}
